﻿@{
    ViewData["Title"] = "ClientsView";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="">
    <div style="display: flex; justify-content: space-between; align-items:center;">
        <div class="layui-input-inline">
            <div style="color: #ccc; font-size: 12px; padding-bottom: 6px;">客户信息(姓名、会员卡号、手机号)</div>
            <select id="clientInfosId" style="width: 80px; height: 30px">
                <option value="1">手机号</option>
                <option value="2">微信呢称</option>
                <option value="3">姓名</option>
                <option value="4">会员卡号</option>
            </select>
            <input type="text" id="clientInfos" style="width: 150px; height: 30px" placeholder="请输入" autocomplete="off">

            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="isShow">展开</button>
        </div>

        <div class="show">
            <div style="color: #ccc; font-size: 12px; padding-bottom: 6px;">客户类型</div>
            <select style="width: 150px; height: 30px" id="clientType">
            </select>
        </div>
        <div class="show">
            <div style="color: #ccc; font-size: 12px; padding-bottom: 6px;">标签</div>
            <select style="width: 150px; height: 30px" id="labelId">
              @*   <option value="">请选择</option>
                <option value="AAA">选项 A</option>
                <option value="BBB">选项 B</option>
                <option value="CCC">选项 C</option> *@
            </select>
        </div>
        <div class="show">
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="isNone">收起</button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-filter="demoTable" lay-event="myBtn">搜索</button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">清空</button>
        </div>
    </div>

    <div style="display:flex; margin-top: 12px">
        <div class="show">
            <div style="color: #ccc; font-size: 12px; padding-bottom: 6px;">性别</div>
            <select style="width: 150px; height: 30px" id="clientSex">
                <option value=0>请选择</option>
                <option value="1">男</option>
                <option value="2">女</option>
            </select>
        </div>
    </div>
    <script type="text/html" id="toolbarDemo">
    <div style="display: flex; justify-content: space-between; margin-top: 12px">
        <div>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">导出会员数据</button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="showLabel" lay-event="getCheckData">打标签</button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">修改等级</button>
                    <button type="button" class="layui-btn layui-btn-primary layui-btn-sm freeze" lay-event="getData" >冻结</button>
                <button type="button" class="layui-btn layui-btn-primary layui-btn-sm unfreeze" lay-event="getDatatwo" >解冻</button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm " lay-event="add12345"  >添加客户</button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">导入客户</button>
        </div>
        <div>
            <button class="layui-btn layui-btn-primary layui-btn-sm jump-btn" type="button" lay-event="jump">标签管理</button>
            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">同步粉丝</button>
        </div>

    </div>
    </script>
     
    <br />
    <br />
</div>
    <table class="layui-hide" e id="demoTable" lay-filter="demoTable"></table>

@* 添加客户弹窗 *@
<div id="ClientAdd" style="display:none;">
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">客户类型</label>
            <div class="layui-input-block">
                <input type="radio" name="clientType" lay-filter="clientType" value="2" title="会员" checked>
                <input type="radio" name="clientType" lay-filter="clientType" value="1" title="普通用户">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">客户姓名</label>
            <div class="layui-input-block">
                <input type="text" name="clientName" required lay-verify="required" placeholder="不超过16个字符" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">手机号码</label>
            <div class="layui-input-block">
                <input type="text" name="clientPhone" required lay-verify="required" placeholder="请输入手机号码" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">成长值</label>
            <div class="layui-input-block">
                <input type="text" name="growthValue" required  placeholder="不填为零，上限10亿" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">可用实余额</label>
            <div class="layui-input-block">
                <input type="text" name="rechargePrice" required  placeholder="不填为零，上限95万" autocomplete="off" class="layui-input">
            </div>
        </div>
       
        <div class="layui-form-item">
            <label class="layui-form-label">可用赠送余额</label>
            <div class="layui-input-block">
                <input type="text" name="fileidsPrice" required placeholder="不填为零，上限95万" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">可用积分</label>
            <div class="layui-input-block">
                <input type="text" name="give" required  placeholder="不填为零，上限10亿" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item condition-field" style="display: none;">
            <label class="layui-form-label" >性别</label>
            <div class="layui-input-block">
                <select name="clientSex2">
                    <option value="0">请选择</option>
                    <option value="1">男</option>
                    <option value="2">女</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item condition-field" style="display: none;">
            <label class="layui-form-label">生日</label>
            <div class="layui-input-block">
                <input type="text" name="clientBirthday" id="date" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item condition-field" style="display: none;">
            <label class="layui-form-label">地址</label>
            <div class="layui-input-block">
                <textarea name="clientaddress" placeholder="请输入详细地址" class="layui-textarea"></textarea>
            </div>      
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>

@* 添加标签弹窗 *@
<div id="LabelAdd" style="display:none;">
    <div class="layui-input-inline">
        <input type="text" id="labelName" placeholder="标签名称" autocomplete="off" class="layui-input">
    </div>
    <button class="layui-btn" lay-submit lay-filter="demoTable" lay-event="myLabelBtn">查询</button>
    <br />
    @* 显示手动标签 *@
    <table class="layui-table" id="demoLabel" lay-filter="demoLabel">
        <tbody>
            <!-- 这里是动态生成的数据 -->
        </tbody>
    </table>
    <button class="layui-btn Label-btn" style="margin-top:10px" lay-event="closelabel">取消</button>
    <button class="layui-btn Label-btn" style="margin-top:10px"  lay-event="addClientLabelModeled">确定</button>
</div>

<script type="text/html" id="ID-table-demo-css-user" >

    <ul id="userInfo" style="display: flex;">
         <img src="~/image/morentouxiang.png" />
            <li style="padding-left: 12px">
                <p><strong>昵称:</strong> {{= d.clientNickName==null?'--':d.clientNickName }}</p>
                <p><strong>姓名:</strong> {{= d.clientName }}</p>
            </li>

    </ul>
</script>
<div id="demo-laypage-all"></div>
<script type="text/html" id="bardemo">
    <div>
        <a style="color:#2589ff" lay-event="yourFunction">详情</a> |
        <a style="color:#2589ff" lay-event="yourFunction">冻结</a> |
          <a style="color:#2589ff" lay-event="yourFunction">送积分</a>
          <br />
        <a style="color:#2589ff" lay-event="yourFunction">送优惠券</a>
          <a style="color:#2589ff" lay-event="yourFunction">充值</a> |
        <a style="color:#2589ff" lay-event="yourFunction">消费</a>
    </div>
</script>
<script>
    function getSelectedIds() {
        var checkstatus = layui.table.checkstatus('demoTable'); // 'demo'为表格的基础参数 id
        // console.log(checkstatus.data); // 获取选中行的数据，即多个行对象
        // console.log(checkstatus.data.length); // 获取选中行数量，可作为是否有选中行的条件
        // console.log(checkstatus.isall); // 表格是否全选

        if (checkstatus.data.length > 0) {
            var idsArray = [];
            for (var i = 0; i < checkstatus.data.length; i++) {
                idsArray.push(checkstatus.data[i].roomId); // 假设每行数据中有一个名为'id'的字段用于存储行的标识
            }
            var ids = idsArray.toString();
            // console.log(ids);
            alert(ids);
        } else {
            alert("请至少选择一行");
        }
    }
    layui.use(['table', 'jquery', 'layer', 'form', 'laypage', 'element'], function () {


        var table = layui.table;
        var $ = layui.jquery;
        var form = layui.form;
        var layer = layui.layer;
        var laypage = layui.laypage;
        var element = layui.element;
        var status = false
        var items = document.getElementsByClassName("show");
        $('#isShow').on('click', function () {
            status = !status
            if (status === false) {
                $('.show').addClass('isShow');
            } else {
                $('.show').removeClass('isShow');
            }
        })

        //$('.jump-btn').click(function () {
        //    window.location.href = 'LabelView';
        //});
        // 手动标签显示
        function manualshow(labelName) {
            $.ajax({
                url: 'http://localhost:5174/api/Labels/GetLabelManual',
                type: 'post',
                contentType: "application/json",
                data: JSON.stringify({ labelName: labelName }),
                headers: {
                    "Authorization": "Bearer " + localStorage.getItem('token')
                },
                async: true,
                success: function (res) {
                    table.render({
                        elem: '#demoLabel',
                        data: res.data,
                        cols: [[
                            { type: 'checkbox' },
                            { field: 'labelName', title: '标签名称', align: 'center' },
                            {
                                field: 'labelType', title: '标签类型', align: 'center', templet: function (d) {
                                    return d.labelType == 1 ? '手动标签' : '自动标签';
                                }
                            },
                        ]],
                        // page: false
                    });
                },
                error: function (error) {
                    console.error(error);
                }
            });
        }
        manualshow($("#labelName").val());
        // 显示
        $(document).on('click', '[lay-event="myLabelBtn"]', function () {
            var labelName = $("#labelName").val();
            // console.log('Label Name:', labelName); // 调试信息
            manualshow(labelName);
        });

        //点击按钮关闭弹框
        $(document).on('click', '[lay-event="closelabel"]', function () {
            layer.close(layer.index);  // layer.index 表示当前显示的弹框索引
        });




        //显示客户信息
        function show() {
            var from = {
                clientInfos: $("#clientInfos").val(),
                clientInfosId: parseInt($("#clientInfosId").val(), 10),
                clientType: parseInt($("#clientType").val(), 10),
                labelId: parseInt($("#labelId").val(), 10) || 0,
                clientSex: parseInt($("#clientSex").val(), 10) || 0,
                ageRange: parseInt($("#ageRange").val(), 10) || 0,
                // lastTime: $("#lastTime").val(),
                startTime: $("#startTime").val(),
                endTime: $("#endTime").val(),
                pageIndex: 1,
                pageSize: 10
            }
            console.log(from)
            $.ajax({
                url: 'http://localhost:5174/api/Clients/GetByWhereClient',
                type: 'post',
                contentType: "application/json",
                data: JSON.stringify(from),
                headers: {
                    "Authorization": "Bearer " + localStorage.getItem('token')
                },
                async: true,
                success: function (res) {
                    tatolcount = res.data.total
                    table.render({
                        elem: '#demoTable',
                        data: res.data.data,
                        toolbar: '#toolbarDemo',
                        cols: [[
                            { type: 'checkbox' },
                            { field: 'Client', title: '客户信息', templet: '#ID-table-demo-css-user', width: 200 },
                            {
                                field: 'clientType', title: '身份', align: 'center', templet: function (d) {
                                    // 根据数据中的某个条件使用三目运算符返回不同的值
                                    return d.clientType == 1 ? '会员' : '普通用户';
                                }
                            },
                            {
                                field: 'isFreeze', title: '状态', align: 'center', templet: function (d) {
                                    return d.isFreeze == true ? '已冻结' : '正常';
                                }
                            },
                            // {
                            //     field: 'memberLevelName', title: '等级', align: 'center'
                            // },
                            {

                                field: 'labelName', title: '标签', align: 'center', templet: function (d) {
                                    if (Array.isArray(d.labelName)) {
                                        return d.labelName.join('<br>');
                                    } else {
                                        return ''; // 或者返回一个默认值，如 '无标签'
                                    }
                                }

                            },
                            {
                                field: 'vipCardNumber', title: '卡号', align: 'center', templet: function (d) {
                                    return d.vipCardNumber == "" ? "--" : d.vipCardNumber
                                }
                            },
                            { field: 'clientPhone', title: '手机', align: 'center' },
                            {
                                field: 'consumPrice', title: '可用余额', align: 'center', templet: function (d) {
                                    return d.consumPrice == 0 ? "￥0.00" : "￥" + d.consumPrice
                                }
                            },
                            { field: 'give', title: '可用积分', align: 'center' },
                            { field: 'consumPrice', title: '累计消费金额', align: 'center' },
                            { field: 'consumNumber', title: '累计消费次数', align: 'center' },
                            { field: 'RefundPrice', title: '累计退款金额', align: 'center' },
                            { field: 'ProtectionNumber', title: '累计维权次数', align: 'center' },
                            { toolbar: '#bardemo', title: '操作', align: 'center' }
                        ]],
                        done: function (res, curr, count) {
                            // 选择客户信息列的单元格并设置高度
                            $('.layui-table-cell[field="Client"]').css('height', '60px');
                        },
                        page: true
                    });

                    console.log(res.data.tatol);
                    console.log(res.data.data)
                },
                error: function (error) {
                    console.error(error);

                }
            })
        }
        //立即调用
        show();



        var ids = [];

        //监听table表格复选框选择（客户表）
        table.on('toolbar(demoTable)', function (obj) {
            var id = obj.config.id;
            console.log(id);
            var checkStatus = table.checkStatus(id);
            console.log(checkStatus)
            var othis = lay(this);
            switch (obj.event) {
                case 'getCheckData':
                    var data = checkStatus.data;
                    console.log(data);
                    // layer.alert(layui.util.escape(JSON.stringify(data)));
                    if (data.length === 0) {
                        alert('请选择打标签的客户');
                    } else {
                        var clientId = data.forEach(function (item) {
                            ids.push(item.clientId)
                            console.log(item.clientId)
                        })
                        console.log(ids)
                        layer.open({
                            type: 1,
                            area: ['650px', '350px'],
                            title: '添加标签',
                            shade: false, // 不显示遮罩
                            content: $('#LabelAdd'), // 捕获的元素
                            end: function () {
                                // layer.msg('关闭后的回调', {icon:6});
                            }
                        });
                    }
                    break;
                case 'getData':
                    var data = checkStatus.data;
                    console.log(data);
                    // layer.alert(layui.util.escape(JSON.stringify(data)));
                    if (data.length === 0) {
                        alert('请选择客户');
                    }
                    else {
                        var clientId = data.forEach(function (item) {
                            ids.push(item.clientId)
                            console.log(item.clientId)
                        })
                        console.log(ids)
                        CheckFreese(1, ids)
                    }
                    break;
                case 'getDatatwo':
                    var data = checkStatus.data;
                    console.log(data);
                    // layer.alert(layui.util.escape(JSON.stringify(data)));
                    if (data.length === 0) {
                        alert('请选择客户');
                    }
                    else {
                        var clientId = data.forEach(function (item) {
                            ids.push(item.clientId)
                            console.log(item.clientId)
                        })
                        console.log(ids)
                        CheckFreese(2, ids)
                    }
                    break;
                case 'add12345':
                    layer.open({
                        type: 1,
                        area: ['800px', '450px'],
                        title: '添加客户',
                        shade: false, // 不显示遮罩
                        content: $('#ClientAdd'), // 捕获的元素
                        end: function () {
                            //  layer.msg('关闭后的回调', {icon:6});
                        },
                        // yes: function (index, layero) {
                        //     // 点击确认按钮的回调
                        //    // layer.close(index); // 关闭弹框
                        // }
                    });
                    break;
                case 'jump':
                    window.location.href = 'LabelView';
                    break;

            };
        });


        // 监听标签类型变化
        form.on('radio(clientSex2)', function (data) {
            if (data.value == 1) {
                $('.condition-field').show();
            } else {
                $('.condition-field').hide();
            }
        });
        // 初始化时检查默认选中的标签类型
        var defaultLabelType = $('input[name="clientSex2"]:checked').val();
        if (defaultLabelType == 1) {
            $('.condition-field').show();
        }
        else {
            $('.condition-field').hide();
        }

        // 冻结客户  解冻客户
        function CheckFreese(isYes, ids) {
            $.ajax({
                url: 'http://localhost:5174/api/Clients/RangeIsFreeze', // 替换为实际的控制器和方法路径
                type: 'post',
                contentType: "application/json",
                data: JSON.stringify({
                    isYes: isYes,
                    ids: ids
                }),
                headers: {
                    "Authorization": "Bearer " + localStorage.getItem('token')
                },
                async: true,
                success: function (res) {
                    alert('操作成功')
                    show()
                }
            });
        }



        // 点击标签确定按钮
        $(document).on('click', '[lay-event="addClientLabelModeled"]', function () {
            var checkStatus = table.checkStatus('demoLabel');  // 将 'yourTableName' 替换为实际的表格 ID
            var selectedRows = checkStatus.data;
            if (selectedRows.length > 0) {
                // 在此处对选中的行数据进行处理
                console.log(selectedRows);
                var lid = [];
                var labelsId = selectedRows.forEach(function (item) {
                    console.log(item.labelId)
                    lid.push(item.labelId)
                })

                $.ajax({
                    url: 'http://localhost:5174/api/Clients/AddRangeClientLabels',
                    type: 'post',
                    contentType: "application/json",
                    data: JSON.stringify({
                        clientIds: ids,
                        labelIds: lid
                    }),
                    headers: {
                        "Authorization": "Bearer " + localStorage.getItem('token')
                    },
                    async: true,
                    success: function (res) {
                        console.log(res);
                        show();
                        layer.close(layer.index);  // layer.index 表示当前显示的弹框索引
                    },
                    error: function (error) {
                        console.error(error);
                    }
                });





            } else {
                layer.msg('请选择标签');
            }
        });



        //条件显示客户信息
        $(document).on('click', '[lay-event="myBtn"]', function () {
            // 处理点击事件的逻辑
            show();
        });

        $(function () {

            getClienttype()
            GetLabel();
        })

        function getClienttype() {
            // 发送 AJAX 请求获取下拉框数据
            $.ajax({
                url: 'http://localhost:5174/api/Clients/GetEnum', // 替换为实际的控制器和方法路径
                type: 'post',
                success: function (res) {
                    // 清空原有的下拉框选项
                    $('#clientType').empty();

                    console.log(res)
                    $('#clientType').append('<option value=0>--请选择--</option>');
                    // 循环添加新的选项
                    $.each(res, function (index, item) {
                        $('#clientType').append('<option value="' + item.value + '">' + item.desc + '</option>');
                    });

                    // 重新渲染下拉框
                    form.render('select');
                    show();
                }
            });
        }

        function GetLabel() {
            // 发送 AJAX 请求获取下拉框数据
            $.ajax({
                url: 'http://localhost:5174/api/Labels/GetLabels', // 替换为实际的控制器和方法路径
                type: 'get',
                success: function (res) {
                    // 清空原有的下拉框选项
                    $('#labelId').empty();

                    console.log(res.data)
                    $('#labelId').append('<option value=0>--请选择--</option>');
                    // 循环添加新的选项
                    $.each(res.data, function (index, item) {
                        $('#labelId').append('<option value="' + item.labelId + '">' + item.labelName + '</option>');
                    });

                    // 重新渲染下拉框
                    form.render('select');
                    show();
                }
            });
        }





        //添加客户
        form.on('submit(formDemo)', function (data) {
            // alert(111)
            data.elem.disabled = true;//防止重复提交
            // 将 labelType 的值从字符串转换为整数
            data.field.labelType = parseInt(data.field.labelType, 10);


            data.field.openCardDate = parseInt(data.field.openCardDate, 10);
            data.field.transactionDate = parseInt(data.field.transactionDate, 10);

            data.field.memberSex = parseBoolean(data.field.memberSex)

            data.field.tradeNumberX = parseInt(data.field.tradeNumberX, 10) || 0;
            data.field.tradeNumberD = parseInt(data.field.tradeNumberD, 10) || 0;

            data.field.replantingDateX = parseFloat(data.field.replantingDateX) || 0;
            data.field.replantingDateD = parseFloat(data.field.replantingDateD) || 0;

            data.field.cumulativeX = parseFloat(data.field.cumulativeX) || 0;
            data.field.cumulativeD = parseFloat(data.field.cumulativeD) || 0;



            data.field.memberSex = parseBoolean(data.field.memberSex) || null;





            console.log(data.field.labelType);
            console.log(data.field.openCardDate);
            console.log(data.field.transactionDate);
            // 创建一个新的对象，只包含非隐藏部分的表单数据  非禁用的条件字段
            var filteredData = {};
            for (var key in data.field) {
                if (!$(`[name="${key}"]`).parents('.condition-field:hidden ').length) {
                    filteredData[key] = data.field[key];
                }
            }
            // // 处理条件字段
            // for (var key in data.field) {
            //     if ($(`[name="${key}"]`).parents('.condition-field:visible ').length) {
            //         filteredData[key] = data.field[key];
            //     }
            // }


            // 使用筛选后的数据进行后续处理，例如发送 AJAX 请求
            console.log(filteredData);





            // 打印表单数据，用于调试
            console.log(JSON.stringify(data.field));
            $.ajax({
                url: 'http://localhost:5174/api/Labels/AddLabel',
                type: 'post',
                contentType: "application/json",
                data: JSON.stringify(filteredData),
                success: function (res) {

                    // 添加成功后的操作
                    if (res.code > 0) {

                        layer.msg("添加成功");
                        window.location.href = 'LabelView';
                    }
                }
            });
            return false;
        });


    });
</script>




<style>
    /*   table tr:first-child{
        height: 30px;
        }

        table tr{
            height: 100px;
        } */
    .isShow {
        display: none;
    }

    .show {
        margin-right: 15px
    }

</style>

<style type="text/css">
    .layui-table-cell {
        height: auto !important;
        white-space: normal;
    }
</style>